#!/bin/sh
#
# Starts audio services
#

. /etc/profile.d/xdg.sh
. /etc/profile.d/dbus.sh

BOARD=$(cat /boot/boot/batocera.board)

start_pipewire() {
    printf "Starting pipewire: "
    start-stop-daemon -S -b -q -m -p /var/run/pipewire.pid --exec /usr/bin/pipewire
    msg=OK

    #Wait till sinks are listed, this means PW is working
    until pactl list sinks-raw | grep -qo sink=
    do
        sleep 0.1
        N=$((N+1))
        test $N -gt 50 && { msg=KO; break; }
    done

    echo "$msg"
}

stop_pipewire() {
    printf "Stopping pipewire: "
    start-stop-daemon -K -q -p /var/run/pipewire.pid
    killall pipewire
    echo "OK"
}

case "$1" in
    start)
        alsactl init # init cards with alsa files
        start_pipewire
    ;;
    stop)
        stop_pipewire
    ;;
    restart|reload)
        stop_pipewire
        start_pipewire
    ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?
